<?php
/*
 *  MAILER is a wrapper class for PHPMailer, 
 *  which helps improve the functionality 
 *  and validation of form inputs, and 
 *  the emailing process.
 * 
 *  AUTHOR: Shawn Wernig
 *  EMAIL: shawn@eggplantstudios.ca
 *  WEBSITE: www.eggplantstudios.ca
 * 
 *  USE:
 *  Create a new eggMailer class, and use the functions:
 *   validate_email_as ($email, $key)
 *   validate_name_as ($string, $key)
 *   validate_textarea_as ($string, $key)
 *  To set the required form values, where $string 
 *  is the raw input value, The validated value 
 *  for $string will replace the $key value in the template.
 * 
 *  Use the PHPMailer AddAddress method to insert addresses,
 * 
 *  Use send_mail($subject, $template = 'contact-form')
 *  to send an email to the addresses added with AddAddress.
 * 
 *  Templates can be found in mailer/templates. $key values in
 *  curly braces { } will be replaced in the template by the
 *  final values, as stored in $mail_vars.
 * 
 */

require_once ('class.phpmailer.php');
require_once ('class.smtp.php');


class eggMailer extends PHPMailer
{
    var $sent = false;
    
    // The Bare Bones...
    private $mail_vars = array(
    'Website' => null,
    'From' => null,         // The mail comes from
    'FromName' => null,
    'To' => null,           // The mail goes to
    'ToName' => null,
    'Body' => null
    );
    var $template_dir;  
    var $template_ext;
    var $Messages= array();
    
    
    public function __construct( $subject )
    {
        $this->isHTML(true);
        
       
        // FOR SMTP EMAIL //
        
        //$this->IsSMTP();
        $this->Host = null;
        $this->Port = null;
        $this->SMTPAuth = false;
        $this->Username = null;
        $this->Password = null;
        
        // $this->Host = "smtpout.secureserver.net";
        // $this->Port = "465";
        // $this->SMTPAuth = true;
        // $this->Username = 'mailer@eggplantstudios.ca';
        // $this->Password = 'ASDG346SGA23Y5GASDGA';
        
        // END SMTP EMAIL //
        $this->template_dir = BASE_PATH . '/mailer/templates/';
        $this->template_ext = ".html";
        $this->Subject = isset( $subject ) ? $subject : 'Web Contact Submission from ' . $_SERVER['SERVER_NAME'];
        $this->Priority = 3;
    }
    
    /*
    //*****************************
    
        SEND THE EMAIL:
        
    \\*****************************
    */
   
    public function send_mail($subject, $template = 'contact-form') {
            // Buffer a template    
            $buffer = $this->buffer_template($template);
            
            if ($buffer) {
                // If a template is available
                $this->Body = $this->parse_variables($buffer, $this->mail_vars);
            } else {
                // No template, do a default
                $this->Body = $this->mail_vars;
            }
           
            if ( $subject ) $mailer->Subject = $subject;
            

            if(!$this->Send()) {
                    $this->add_message('There was a problem sending this mail, please try again later.');
                    return false;    
            } else  {
                    $this->sent = true;
                    $this->add_message('Your message has been sent successfully.');
                    return true;
            }
            $this->ClearAddresses();
            $this->ClearAttachments();   
    }
    
    
    /*
    //*****************************
    
        TEMPLATE RELATED METHODS
        
    \\*****************************
    */
    private function buffer_template($file) {
        $path = $this->template_dir . $file . $this->template_ext;
        if( is_readable( $path ) ) {
            $this->buffer = file_get_contents( $path );
                return $this->buffer;
        } else {
            $this->add_message('FATAL ERROR: Template ' . $path   . ' does not exist!');
        }
    }
    
    function parse_variables($input, $array) {   
        $search = preg_match_all('/{.*?}/', $input, $matches);
        
        for($i = 0; $i < $search; $i++) {
            $matches[0][$i] = str_replace(array('{', '}'), null, $matches[0][$i]);
        }
        
        foreach($matches[0] as $value) {
        $input = str_replace('{' . $value . '}', $array[$value], $input);
        }
        
        return $input;
    }

   
   /*
    //*****************************
    
        ERRORS
        
    \\*****************************
    */
    public function has_messages() {
        if ($this->Messages) { return TRUE; }
        else { return false; }
    }

    public function add_message($string) {
        if($string) $this->Messages[] = $string;
    }
    
    public function show_messages() {
        
        if(!empty($this->Messages)) {
            
            echo ($this->sent) ? '<ul id="form-success">' : '<ul id="form-error">';
            
            foreach ( $this->Messages as $message ){
                echo "<li>{$message}</li>";
            }
            echo '</ul>';
        }
    }
    
    
    /*
    //*****************************
    
        VALIDATION HELPER METHODS
        
    \\*****************************
   */
    private function clean_var($data){
        if ( $data  ) {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
        } else {
            return false;
        }
    }
    private function check_var_for_html($string){
        if ( preg_match("/([\<])([^\>]{1,})*([\>])/i", $string) ) {
            return false;
        } else {
            return $string;
        }
    } 
    /*
    //*****************************
    
        HARD SET KEYS AND VALUES
        
    \\*****************************
    */
    private function validate_value_as ($string, $key) {
        if ( $string = $this->check_var_for_html($string) ) {
            $this->mail_vars[$key] = $string;
            return $string;
        }
        return false;
    }
    private function set_value_as ($string, $key) {
        if ( $string && $key ) {
            $this->mail_vars[$key] = $string;
            return true;
        }
        return false;
    }
   
    /*
    //*****************************
    
        GENERAL INPUT VALIDATION
            - CHECKS STRICTLY FOR HTML INJECTION
        
    \\*****************************
    */
      
   public function validate_input ($string) {
       if ( $string = $this->check_var_for_html($string) ) {
           $string = $this->clean_var($string);       
           if( !empty($string) ) {
                $string = filter_var($string, FILTER_SANITIZE_STRING);
                return $string;
           }
        } 
       
        return false;
   }
  
   
    public function validate_input_as ($string, $key) {
        //array to csv
         if (is_array($string) ) $string = implode(", ", $string);
         if ( $this->set_value_as( $this->validate_input($string), $key) ) {
            return $string;
         } else {
            $this->add_message($string . ' is <strong>NOT</strong> a valid input.');
            return false;
         }
    }
    
    /*
    //*****************************
    
        EMAIL RELATED
        
    \\*****************************
    
    
    public function validate_email ($email) {
        if( $string = $this->clean_var($email) ) {
            $email = filter_var($email, FILTER_SANITIZE_EMAIL); 
            if ( filter_var($email, FILTER_VALIDATE_EMAIL) ) return $email;
        } 
        return false;
    }
            
    public function validate_email_as ($email, $key) {
        if( $this->set_value_as( $this->validate_email($email), $key ) ) {
            return $email;
        } else {
            $this->add_message($email . ' is <strong>NOT</strong> a valid email address.');
            return false;
        }
    }*/
    
    
    /*
    //*****************************
    
        NAME VALIDATION
            - No funny business allowed
            - Only letters, hyphens and spaces allowed
        
    \\*****************************
    
    public function validate_name ($string) {
        
        if( $string = $this->clean_var($string)) {
            $string = filter_var($string, FILTER_SANITIZE_STRING);
            if ( !preg_match("/[^a-zA-Z- ]/", $string ) ) return $string;
        } 
        return false;
    }
    
    public function validate_name_as ($string, $key) {
        
         if ( $this->set_value_as( $this->validate_name($string), $key)) {
            return $string;
         } else {
            $this->add_message($string . ' is <strong>NOT</strong> a valid name.');
            return false;
         }         
      
    }*/
   
    /*
    //*****************************
    
        TEXT-AREA
            - No funny business allowed
            - Only letters, hyphens and spaces allowed
        
    \\*****************************
    
    public function validate_textarea_as ($string, $key) {
         if ( $this->set_value_as( $this->validate_input($string), $key) ) {
            $this->mail_vars[$key] = $string;
            return $string;
         } else {
            $this->add_message($string . ' is <strong>NOT</strong> a valid message. Please don\'t insert HTML characters into your comments.');
            return false;
         }
    }*/
    
    /*
    //*****************************
    
        URL VALIDATION
            TODO: ACTUALLY DO THIS...
        
    \\*****************************
   
   
    public function validate_website_as ($string, $key) {
        $this->mail_vars[$key] = $string;
        return $string;
    }    */
}

?>